package compile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2023/12/21 19:48
 */
public class CommandUtil {
    //1.通过runtime类，得到runtime实例，执行exec方法
    //2.能够获取到标准输出，并写入到指定文件中
    //3.获取到标准错误，并写入到指定文件中
    //4.等待子进程结束，拿到子进程状态码并返回
    public static int run(String cmd,String stdoutFile,String stderrFile){
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            if (stdoutFile!=null){
                InputStream stdoutFrom = process.getInputStream();
                FileOutputStream stdoutTo = new FileOutputStream(stdoutFile);
                while (true){
                    int ch = stdoutFrom.read();
                    if (ch==-1){
                        break;
                    }
                    stdoutTo.write(ch);
                }
                stdoutFrom.close();
                stdoutTo.close();
            }

            //获取标准错误
            if (stderrFile!=null){
                InputStream stderrFrom = process.getErrorStream();
                FileOutputStream stderrTo = new FileOutputStream(stderrFile);
                while (true){
                    int ch = stderrFrom.read();
                    if (ch==-1){
                        break;
                    }
                    stderrTo.write(ch);
                }
                stderrFrom.close();
                stderrTo.close();
            }


            //4.等待子进程结束，拿到子进程状态码并返回
            int exitCode = process.waitFor();
            return exitCode;


        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1;
    }


    public static void main(String[] args) {
        CommandUtil.run("javac1","./tmp/s.txt","./tmp/e.txt");
    }



}
